package com.zs.common.util;

import org.apache.commons.compress.utils.Lists;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

public class ImageUtil {


    public static BufferedImage mergeUrls(List<String> urls,boolean isVertical,Color defaultWhite) throws IOException {

        List<BufferedImage> imgs = Lists.newArrayList();
        int concatWidth = 0;
        int concatHeight = 0;
        int maxWidth = 0;
        int maxHeight = 0;
        for (String u : urls) {
            BufferedImage image = ImageIO.read(new URL(u));
            concatWidth += image.getWidth();
            concatHeight += image.getHeight();
            if (image.getWidth() > maxWidth) {
                maxWidth = image.getWidth();
            }
            if (image.getHeight() > maxHeight) {
                maxHeight = image.getHeight();
            }
            imgs.add(image);
        }

        BufferedImage concatImage = new BufferedImage(isVertical ? maxWidth : concatWidth,
                isVertical ? concatHeight : maxHeight, BufferedImage.TYPE_INT_RGB);
        ;

        Graphics2D g2d = concatImage.createGraphics();
        g2d.setBackground(defaultWhite==null?Color.white:defaultWhite);
        g2d.clearRect(0, 0, isVertical?maxWidth:concatWidth, isVertical?concatHeight:maxHeight);
        int lastValue = 0;
        for (BufferedImage img : imgs) {
            g2d.drawImage(img, isVertical?0:lastValue, isVertical?lastValue:0, null);
            lastValue += (isVertical?img.getHeight():img.getWidth());
        }
        g2d.dispose();
        return concatImage;
    }

}
